package concurrent;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadPoolExecutorDemo {
	public static void main(String[] args) {
		System.out.println("a".getBytes().length);
		System.out.println("好".getBytes().length);
		System.out.println("譞".getBytes().length);
		System.out.println("好人".getBytes().length);
		//t2();
	}

	public static void t2() {
		BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<Runnable>();
		ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(3, 6,
				1000L, TimeUnit.DAYS, workQueue) {

			@Override
			protected void beforeExecute(Thread t, Runnable r) {
				System.out.println(t.getName());
				System.out.println("before");
				super.beforeExecute(t, r);
			}

			@Override
			protected void afterExecute(Runnable r, Throwable t) {
				System.out.println("after");
				super.afterExecute(r, t);
			}
		};
		threadPoolExecutor.execute(new Runnable() {

			@Override
			public void run() {
					try {
						Thread.sleep(2000L);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				System.out.println("haha");

			}

		});
		//threadPoolExecutor.shutdown();
		threadPoolExecutor.shutdownNow();
	}

	public void t1() {
		// 创建一个固定大小的线程池
		ExecutorService executor = Executors.newFixedThreadPool(5);

		for (int i = 0; i < 10; i++) {
			Runnable worker = new WorkerThread("" + i);
			executor.execute(worker);
		}
		executor.shutdown();
		while (!executor.isTerminated()) {
		}
		System.out.println("Finished all threads");
	}
}

class WorkerThread implements Runnable {

	private String command;

	public WorkerThread(String s) {
		this.command = s;
	}

	@Override
	public void run() {
		System.out.println(Thread.currentThread().getName()
				+ " Start. Command = " + command);
		processCommand();
		System.out.println(Thread.currentThread().getName() + " End.");
	}

	private void processCommand() {
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	@Override
	public String toString() {
		return this.command;
	}
}
